package com.projectexercise.test.verify;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class VerifyController2 {
    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        response.setContentType("image/jpeg"); // 设置为图片格式
        response.setHeader("Progma","No-cache");// 设置禁止缓存
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        try {
            lineCaptcha.write(response.getOutputStream());
            session.setAttribute("captcha", lineCaptcha.getCode());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @RequestMapping("/check")
    public Boolean check(String inputCode, HttpSession httpSession){
        String captcha = (String) httpSession.getAttribute("captcha");
        if(!StringUtils.hasLength(inputCode)){
            return false;
        }
        if(captcha == null || captcha.equalsIgnoreCase(inputCode)){
            return true;
        }
        return false;
    }
}
